#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
订单数据模型
"""

from database import db
from datetime import datetime
import uuid

class Order(db.Model):
    __tablename__ = 'orders'
    
    id = db.Column(db.Integer, primary_key=True)
    order_no = db.Column(db.String(32), unique=True, nullable=False, comment='订单号')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    table_id = db.Column(db.Integer, db.ForeignKey('billiard_tables.id'), nullable=True, comment='台球桌ID')
    
    # 订单信息
    order_type = db.Column(db.String(20), nullable=False, comment='订单类型：table_rental台桌租赁，recharge充值，membership会员')
    title = db.Column(db.String(200), nullable=False, comment='订单标题')
    description = db.Column(db.Text, nullable=True, comment='订单描述')
    
    # 金额信息
    original_amount = db.Column(db.DECIMAL(10, 2), nullable=False, comment='原价')
    discount_amount = db.Column(db.DECIMAL(10, 2), default=0.00, comment='优惠金额')
    final_amount = db.Column(db.DECIMAL(10, 2), nullable=False, comment='实付金额')
    
    # 支付信息
    payment_method = db.Column(db.String(20), nullable=True, comment='支付方式：wechat微信，alipay支付宝，balance余额')
    payment_status = db.Column(db.String(20), default='pending', comment='支付状态：pending待支付，paid已支付，failed失败，refunded已退款')
    paid_at = db.Column(db.DateTime, nullable=True, comment='支付时间')
    transaction_id = db.Column(db.String(100), nullable=True, comment='第三方交易号')
    
    # 租赁信息（台桌订单专用）
    start_time = db.Column(db.DateTime, nullable=True, comment='开始时间')
    end_time = db.Column(db.DateTime, nullable=True, comment='结束时间')
    duration_minutes = db.Column(db.Integer, nullable=True, comment='时长（分钟）')
    hourly_rate = db.Column(db.DECIMAL(10, 2), nullable=True, comment='小时费率')
    
    # 订单状态
    status = db.Column(db.String(20), default='created', comment='订单状态：created已创建，confirmed已确认，in_progress进行中，completed已完成，cancelled已取消')
    
    # 系统字段
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    remark = db.Column(db.Text, nullable=True, comment='备注')
    
    def __init__(self, **kwargs):
        super(Order, self).__init__(**kwargs)
        if not self.order_no:
            self.order_no = self.generate_order_no()
    
    @staticmethod
    def generate_order_no():
        """生成订单号"""
        prefix = datetime.now().strftime('%Y%m%d')
        suffix = str(uuid.uuid4()).replace('-', '')[:8].upper()
        return f'BH{prefix}{suffix}'
    
    def to_dict(self):
        return {
            'id': self.id,
            'order_no': self.order_no,
            'user_id': self.user_id,
            'table_id': self.table_id,
            'order_type': self.order_type,
            'title': self.title,
            'description': self.description,
            'original_amount': float(self.original_amount),
            'discount_amount': float(self.discount_amount),
            'final_amount': float(self.final_amount),
            'payment_method': self.payment_method,
            'payment_status': self.payment_status,
            'paid_at': self.paid_at.isoformat() if self.paid_at else None,
            'transaction_id': self.transaction_id,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'duration_minutes': self.duration_minutes,
            'hourly_rate': float(self.hourly_rate) if self.hourly_rate else None,
            'status': self.status,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'remark': self.remark,
            'user': self.user.to_dict() if self.user else None,
            'table': self.table.to_dict() if self.table else None
        }
    
    def __repr__(self):
        return f'<Order {self.order_no}>'